package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryTodayBest(Long toUserId) {
//        db.recommend_user.find({toUserId:1}).sort({score:-1}).limit(1)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        query.limit(1);
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public PageResult queryRecommendation(Long toUserId, Integer page, Integer pagesize) {
//        第一页：
//        db.recommend_user.find({toUserId:1}).sort({score:-1}).limit(10).skip(1)
//        第二页：
//        db.recommend_user.find({toUserId:1}).sort({score:-1}).limit(10).skip(11)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        long count = mongoTemplate.count(query, RecommendUser.class);
        query.limit(pagesize).skip( (page-1)*pagesize + 1).with(Sort.by(Sort.Direction.DESC,"score"));
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);
        return new PageResult(page,pagesize,(int)count, list);
    }

    @Override
    public Long queryScore(Long toUserId, Long userId) {
//        select * from recommend_user where toUserId=UserHolder.getUserId() and userId=userId
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser==null){
            return RandomUtils.nextLong(80,90);
        }
        return recommendUser.getScore().longValue();
    }

    @Override
    public void delete(Long userId, Long toUserId) {
 //        删除推荐数据 delete from recommend_user where userId={userId} and toUserId=UserHolder.getUserid()
        Query query = new Query(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        mongoTemplate.remove(query,RecommendUser.class);
    }
}
